package com.bdqn.petmalldemo.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bdqn.petmalldemo.common.KetaiException;
import com.bdqn.petmalldemo.common.ResultCodeEnum;
import com.bdqn.petmalldemo.entity.Order;
import com.bdqn.petmalldemo.entity.Pay;
import com.bdqn.petmalldemo.mapper.OrderMapper;
import com.bdqn.petmalldemo.mapper.PayMapper;
import com.bdqn.petmalldemo.service.PayService;
import com.bdqn.petmalldemo.utils.AliPayUtil;
import com.bdqn.petmalldemo.utils.QRCodeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Lenovo
 * @since 2020-02-10
 */
@Service
@Slf4j
public class PayServiceImpl extends ServiceImpl<PayMapper, Pay> implements PayService {

    @Resource
    private OrderMapper orderMapper;
    @Resource
    private AliPayUtil aliPayUtil;

 /*   @Value("${qr.path}")
    private String qrPath;*/
    @Override
    public String addPay(String orderId) {
        //1.先根据orderId查询订单信息
        Order order = orderMapper.selectById(orderId);
        //2.发起支付请求(预支付)
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipaydev.com/gateway.do",
                "2016101800713592",
                "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCiAk+/tfbLbJAQV8Fd0TqrqCl3wThHH+1S3E3rgWBpVIRiBTbN2uP78JFkNGuHyWTStiZf53UZQHkmVWOf/gx6ogX/VxLwnaDfp/oZ9uf57X/8lmbTKWOQPT/ecdA7268pHPA1zJvIjNyXZE0jhz0hY3aI3FS+78rX0Yw+fPQpfotndg/wsTkgn6PoXCriloIkYCT8dRg7jqk7uBTZuXKYWF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uO9nb7L3/sEwOxuUthNBfTbq+DFVbcFWzjsCVx16WfSjwZQJ+JyQonWtu1l4mWpEbWzI6rTCTPjLhx5b99MuxC1UPPUOUdUBC8t8CgYB8bxLy9MpLnR6ZHAbaZbb3rjf9TIJ/g+4B54pow7QaH7awx63B3y8m7W0i8g6rPLc+gIfgjYBDC3C2Dz+BGKp0SUf4HIW12dW6CbOydJ5CaNp3C3/uRvaVIFzx9nVlX18I9s5w9lKkSnia8tAuWyhLF28yHNKt5auLJdMVKlGaLg==",
                //"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzAWYToJEco4B+B29lvpg/n3ep/lp9uO7Dzs41PtbEWQrqVf4U6z0sdsoMjJ0tXetphPY506Re0tCW/kCCegcJH1LfykZ3JbMAaG8bL/dRh9LfP1Jf3bjmLl3TXoo8tbn4Bk2UH/1SiHjZ6hfbDoUgJ3xb+7BfawXp0qZH+IUcM2Yo5An035N1qTpItOrOc8G3k7fnWvJ/g6PVbOF2RXN8cAv0div+lRX97jh0z
                "json",
                "UTF-8",
                "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAg0KcspaZsp5GcGJDrgBevErggoL4wZ7b/sJAl4IaxozZznDkWef6wbMeeiEVGci76git8a+cjUWJdvx0V7sD0E7KYFxVUsduSfq3aA33f+/j21U94Rl+WLoSotT8b75BM8mlO7f/tirVCFNjvA/6HRAf6sFC2mwi480idgpQfKR+/0x9N277xkDIQe+X1HMde3QI55IQzSB8YCwsbaAC+NXsNe2jgMMEVBstyThN7FbfJmyITl1OaWOmZjPtOZIwZ/DQ6EUY08HR0pztZx5V6Y7oeVtqxQmzzFDq+jeP907QxxbfzdbajP61oumWU9MxEP8oMa8fuINo1KauvlG9IwIDAQAB",
                //"B8YCwsbaAC+NXsNe2jgMMEVBstyThN7FbfJmyITl1OaWOmZjPtOZIwZ/DQ6EUY08HR0pztZx5V6Y7oeVtqxQmzzFDq+jeP907QxxbfzdbajP61oumWU9MxEP8oMa8fuINo1KauvlG9IwIDAQAB",
                "RSA2"); //获得初始化的AlipayClient
        //预支付request
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        //绑定参数,订单号,付款总价,订单名称,商家id，超时时间
        Map<String,Object> map=new HashMap<>(16);
        map.put("out_trade_no",order.getId());
        map.put("total_amount",order.getPayment().toString());
        map.put("subject","萌宠中心-"+order.getOrderNo()+"-订单");
        map.put("store_id","2088102180096283");
        map.put("timeout_express","90m");
        request.setBizContent(JSONObject.toJSONString(map));
        AlipayTradePrecreateResponse response = null;
        String qrImage=null;
        try {
            response=alipayClient.execute(request);
            log.info("预支付响应数据:{}",response);
            if (response.isSuccess()) {
                //付款二维码链接
                String qrCode = response.getQrCode();
                //指定编码地址
                String destPath="F:\\zy\\Y2\\xm\\pet-mall-demo\\target\\classes\\static\\upload\\alipay\\"+orderId+".jpg";
                File file = new File(destPath);
                if (file.exists()) {
                    file.delete();
                }
                //准备生成二维码
                QRCodeUtil.encode(qrCode,destPath);
                //异步执行支付状态检查
                aliPayUtil.checkPayResult(order);
                qrImage= orderId+".jpg";
            }else {
                log.error("响应异常信息:{}",response.getSubMsg());
                throw new KetaiException(ResultCodeEnum.PREPAYMENT_FAILED);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.print(response.getBody());
        return qrImage;
    }


}
